package com.sixks.app.api;

import com.alibaba.fastjson.JSON;
import com.sixks.app.AliExpressConstant;
import com.sixks.app.api.utils.CommonUtil;
import com.sixks.app.mvc.cmd.exception.ExpressAPIException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.util.Map;


/**
 * api调用的服务类
 */
public class ApiCallService {

    /**
     * 调用api测试
     *
     * @param urlHead      请求的url到openapi的部分，如http://gw.open.1688.com/openapi/
     * @param urlPath      protocol/version/namespace/name/appKey
     * @param appSecretKey 测试的app密钥，如果为空表示不需要签名
     * @param params       api请求参数map。如果api需要用户授权访问，那么必须完成授权流程，params中必须包含access_token参数
     * @return json格式的调用结果
     */
    public static String callApiTest(String urlHead, String urlPath, String appSecretKey, Map<String, String> params) throws ExpressAPIException {
        final HttpClient httpClient = new HttpClient();
        final PostMethod method = new PostMethod(urlHead + urlPath);
        method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                method.setParameter(entry.getKey(), entry.getValue());
            }
        }
        if (appSecretKey != null) {
            method.setParameter("_aop_signature", CommonUtil.signatureWithParamsAndUrlPath(urlPath, params, appSecretKey));
        }
        String response = "";
        try {
            int status = httpClient.executeMethod(method);
            if (status >= 300 || status < 200) {
                String msg = method.getResponseBodyAsString();
                Map<String,String> map = JSON.parseObject(msg, Map.class);
                throw new ExpressAPIException(map.get("error_code"),map.get("error_message"));
            }
            response = CommonUtil.parserResponse(method);
        } catch (HttpException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            method.releaseConnection();
        }
        return response;
    }

    /**
     * 图片银行
     *
     * @param params
     * @param image
     * @return
     */
    public static String callUploadImage2Bank(Map<String, String> params, byte[] image) throws ExpressAPIException {

        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod("http://gw.api.alibaba.com/fileapi/param2/1/aliexpress.open/api.uploadImage/"+ AliExpressConstant.APP_KEY+"?access_token=" + params.get("access_token") + "&fileName=" + params.get("fileName"));
        postMethod.setRequestHeader("Content-type", "application/octet-stream");


        postMethod.setRequestEntity(new ByteArrayRequestEntity(image));


        String response = "";
        try {
            int statusCode = client.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Not 200");
            }

            if (statusCode >= 300 || statusCode < 200) {
                String msg = postMethod.getResponseBodyAsString();
                Map<String,String> map = JSON.parseObject(msg, Map.class);
                throw new ExpressAPIException(map.get("error_code"),map.get("error_message"));
            }
            response = CommonUtil.parserResponse(postMethod);

        } catch (HttpException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            postMethod.releaseConnection();
        }
        return response;
    }
}